package customer

import (
	"context"
	"errors"
	"fmt"
	"sieve_admin_server_userpass/lib/log"
	"strings"
	"sync"
)

var (
	businessPriceCronOnce = sync.Once{}
)

func (a *BusinessPriceSrv) init() error {

	var (
		initCount = 1
		wp        = sync.WaitGroup{}
		logMsg    []string
	)

	wp.Add(initCount)
	go func() {
		err := a.SyncBusinessPriceUserCount()
		logMsg = append(logMsg, fmt.Sprintf("%+v", err))
		wp.Done()
	}()

	wp.Wait()

	return errors.New(strings.Join(logMsg, ","))
}

func (a *BusinessPriceSrv) Cron() error {

	businessPriceCronOnce.Do(func() {
		log.Info(fmt.Sprintf("%v", a.init()))
	})

	return nil
}

func (a *BusinessPriceSrv) SyncBusinessPriceUserCount(args ...interface{}) error {

	var (
		execSQL = fmt.Sprintf(`
UPDATE 
	business_price_scheme
INNER JOIN (
SELECT 
	business_price_scheme.id as business_price_id,
	COUNT(user.id) AS user_count
FROM
	business_price_scheme
LEFT JOIN user ON business_price_scheme.id = user.business_price_id
AND user.deleted = 0
GROUP BY business_price_scheme.id
) user_business_price ON user_business_price.business_price_id = business_price_scheme.id AND business_price_scheme.deleted = 0
SET business_price_scheme.user_count = user_business_price.user_count;
`)
	)

	_, err := a.BusinessPriceSchemeRepo.ExecRaw(context.Background(), execSQL)
	return err
}
